package com.example.myapplication;

import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;

public class MainActivity extends AppCompatActivity {
     private WebView my_webview;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        my_webview=findViewById(R.id.my_webview);
        my_webview.addJavascriptInterface(new JStoAndroid(MainActivity.this),"text");
        my_webview.loadUrl("file:///android_asset/test.html");
        my_webview.getSettings().setJavaScriptEnabled(true);
        my_webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        my_webview.setWebChromeClient(new WebChromeClient(){
            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result){
                AlertDialog alertDialog=new AlertDialog.Builder(MainActivity.this)
                        .setTitle("JS Alert")
                        .setMessage(message)
                        .setCancelable(true)
                        .create();
                alertDialog.show();
                return  true;
            }
        });
        findViewById(R.id.btn_callwebjs).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                my_webview.evaluateJavascript("javascript:callJS()", new ValueCallback<String>() {
                    @Override
                    public void onReceiveValue(String value) {
                    }
                });
            }
        });

    }
}
